/*
 * Copyright (c) 2021
 * User:LENOVO
 * File:翻转字符串中的单词.java
 * Date:2021/02/18 14:16:18
 */

package org.bytedance.字符串;

/**
 * 给定一个字符串，逐个翻转字符串中的每个单词。
 * <p>
 * 说明：
 * <p>
 * 无空格字符构成一个 单词 。
 * 输入字符串可以在前面或者后面包含多余的空格，但是反转后的字符不能包括。
 * 如果两个单词间有多余的空格，将反转后单词间的空格减少到只含一个。
 */
public class 翻转字符串中的单词 {


    public static void main(String[] args) {
        翻转字符串中的单词 instance = new 翻转字符串中的单词();
        String input1 = "the sky is blue";
        String s = instance.reverseWords(input1);
        System.out.println(s);

        s = instance.reverseWords2(input1);
        System.out.println(s);

        input1 = "  hello world!  ";
        s = instance.reverseWords(input1);
        System.out.println(s);
        s = instance.reverseWords2(input1);
        System.out.println(s);

        input1 = "a good   example";
        s = instance.reverseWords(input1);
        System.out.println(s);
        s = instance.reverseWords2(input1);
        System.out.println(s);
    }

    public String reverseWords(String s) {
        if (null == s || s.isEmpty()) throw new IllegalArgumentException("bad param");
        s = s.trim();
        String[] s1 = s.split("\\s+");
        if (s1.length == 1) return s1[0];
        StringBuilder sb = new StringBuilder();
        int length = s1.length;
        while (--length >= 0) {
            sb.append(s1[length]).append(" ");
        }
        return sb.toString();
    }


    /**
     * 双指针实现（效率也不高）
     * @param s
     * @return
     */
    public String reverseWords2(String s) {
        if (null == s || s.isEmpty()) throw new IllegalArgumentException("bad param");
        s = s.trim();
        String[] s1 = s.split("\\s+");
        if (s1.length == 1) return s1[0];
        int left = 0, right = s1.length - 1;
        StringBuilder sb = new StringBuilder();
        while (left < right) {
            String tmp = s1[left];
            s1[left] = s1[right];
            s1[right] = tmp;
            sb.append(s1[left]).append(" ");
            left++;
            right--;
        }
        while (left < s1.length) {
            sb.append(s1[left++]).append(" ");
        }
        return sb.toString();
    }
}
